package cloud.lysky.java.on.async.completable_future;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author luoly
 * @describe
 * @date 2022-08-25 9:27
 **/
public class Shop {

    private String name;



    public Shop(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }

    public double getPrice(String product){
        return calculatePrice(product);
    }

    public Future<Double> getPriceAsync(String product){
        //创建CompletableFuture对象，它会包含计算结果
        CompletableFuture<Double> futurePrice = new CompletableFuture<>();
        new Thread(() ->{
            try {
                double price = calculatePrice(product); //在另一个线程中以异步方式执行计算
                futurePrice.complete(price);
            } catch (Exception e) {
                futurePrice.completeExceptionally(e);//否则就抛出导致失败的异常，完成这次Future操作
            }
        }).start();
        return futurePrice;
    }

    public Future<Double> getPriceAsyncUp(String product){
        return CompletableFuture.supplyAsync(()-> calculatePrice(product));
    }

    private double calculatePrice(String product) {
        delay();
        Random random = new Random();
        return random.nextDouble() * product.charAt(0) + product.charAt(1);
    }

    public static void delay(){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}